const { bookAPI } = require('../../utils/api.js');

Page({
  data: {
    isbn: '',
    book: null,
    summaryNodes: [],
    categoryList: [],
    loading: false,
    error: '',
    statusBarHeight: 20,
    headerPaddingPx: 60,
    footerPaddingPx: 160
  },

  onLoad(options) {
    // 读取状态栏高度，用于左上角标题安全避让
    try {
      const sys = wx.getSystemInfoSync();
      if (sys && typeof sys.statusBarHeight === 'number') {
        // rpx -> px 换算：1rpx = windowWidth / 750 px
        const rpx = sys.windowWidth ? (sys.windowWidth / 750) : 1;
        // 精确避让：头部高度为 64rpx
        const headerPx = Math.round(rpx * 64);
        // 底部安全区（iOS 带 Home 指示条），再加一些缓冲，避免被遮挡
        const safeBottomInset = (sys.safeArea && typeof sys.safeArea.bottom === 'number' && typeof sys.screenHeight === 'number')
          ? (sys.screenHeight - sys.safeArea.bottom) : 0;
        const footerPad = Math.max(120, safeBottomInset + 100);
        this.setData({ 
          statusBarHeight: sys.statusBarHeight,
          headerPaddingPx: sys.statusBarHeight + headerPx,
          footerPaddingPx: footerPad
        });
      }
    } catch (_) {}

    const isbn = (options && options.isbn) ? options.isbn : '';
    if (isbn) this.setData({ isbn });

    // 优先使用 eventChannel 传递的数据
    try {
      const channel = this.getOpenerEventChannel && this.getOpenerEventChannel();
      if (channel && channel.on) {
        channel.on('bookData', ({ book }) => {
          if (book) {
            // 先展示传入的数据
            this.setData({ book });
            this.updateSummaryNodes();
            this.updateCategoryList();
            // 若缺少简介且有ISBN，则拉取后端完整数据并合并
            const hasSummary = !!(book.summary);
            if (!hasSummary && isbn) {
              this.fetchBook(isbn);
            }
          } else if (isbn) {
            this.fetchBook(isbn);
          }
        });
        return;
      }
    } catch (_) {}

    // 如果没有 channel 数据，则根据 isbn 再查询一次
    if (isbn) {
      this.fetchBook(isbn);
    }
  },

  fetchBook(isbn13) {
    this.setData({ loading: true, error: '' });
    bookAPI.getByIsbn(isbn13)
      .then((resp) => {
        const raw = resp && resp.data ? resp.data : null;
        // 归一化字段，兼容后端不同命名
        const normalize = (b) => {
          if (!b) return null;
          const n = {
            title: b.title ?? b.name ?? b.bookName ?? '',
            authors: b.authors ?? b.author ?? b.authorsZh ?? '',
            publisher: b.publisher ?? b.press ?? b.publisherName ?? '',
            publishedDate: b.publishedDate ?? b.publishDate ?? b.publicationDate ?? b.pubdate ?? '',
            isbn13: b.isbn13 ?? b.isbn ?? b.isbn_13 ?? '',
            pageCount: b.pageCount ?? b.pages ?? b.page_count ?? '',
            language: b.language ?? b.lang ?? b.languageZh ?? '',
            categories: b.categories ?? b.category ?? b.tags ?? '',
            coverUrl: b.coverUrl ?? b.cover ?? b.image ?? b.coverImage ?? '',
            summary: b.summary ?? b.description ?? b.brief ?? b.intro ?? b.abstract ?? ''
          };
          return n;
        };
        const normalized = normalize(raw);
        const merged = { ...(this.data.book || {}), ...(normalized || {}) };
        this.setData({ book: merged, loading: false });
        this.updateSummaryNodes();
        this.updateCategoryList();
      })
      .catch((err) => {
        const msg = err && (err.message || err.msg) ? (err.message || err.msg) : '查询失败';
        this.setData({ error: msg, loading: false });
      });
  },

  // 根据 book.summary 生成 rich-text nodes，支持换行与长文显示
  updateSummaryNodes() {
    try {
      const s = (this.data.book && this.data.book.summary) ? String(this.data.book.summary) : '';
      if (!s) {
        this.setData({ summaryNodes: [{ type: 'text', text: '暂无简介' }] });
        return;
      }
      const lines = s.split(/\n+/);
      // 将样式交给 WXSS：仅保留段落间距，让主题样式统一生效
      const nodes = lines.map(line => ({ name: 'p', attrs: { style: 'margin:0 0 18px;' }, children: [{ type: 'text', text: line }] }));
      this.setData({ summaryNodes: nodes });
    } catch (_) {
      this.setData({ summaryNodes: [{ type: 'text', text: '暂无简介' }] });
    }
  },

  // 解析分类为 chips 列表
  updateCategoryList() {
    try {
      const cats = this.data.book ? this.data.book.categories : '';
      let list = [];
      if (Array.isArray(cats)) {
        list = cats;
      } else if (typeof cats === 'string') {
        list = cats.split(/[\n,，;|\/\s]+/).map(s => s.trim()).filter(Boolean);
      }
      // 去重并限制数量以避免过长
      const seen = new Set();
      const uniq = [];
      for (const c of list) {
        const key = c.toLowerCase();
        if (!seen.has(key)) { seen.add(key); uniq.push(c); }
        if (uniq.length >= 12) break;
      }
      this.setData({ categoryList: uniq });
    } catch (_) {
      this.setData({ categoryList: [] });
    }
  },

  goBack() {
    const pages = getCurrentPages();
    if (pages && pages.length > 1) {
      wx.navigateBack({ delta: 1 });
    } else {
      wx.reLaunch({ url: '/pages/index/index' });
    }
  }
});